﻿#include "mswidget.h"
#include "ui_mswidget.h"

#include <QFileDialog>
#include <QMessageBox>
#include <QTextDocument>
#include <QTextBlock>

int MSwidget::identification=0;
MSwidget::MSwidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MSwidget)
{
    ui->setupUi(this);
    MaterialSend();
}

MSwidget::~MSwidget()
{
    delete ui;
}


void MSwidget::MaterialSend()
{
    ui->MSstartdE->setDate(QDate::currentDate());
    ui->MSenddE->setDate(QDate::currentDate());
    ui->MSstartdE->setEnabled(false);
    ui->MSenddE->setEnabled(false);
    ui->SendTW->horizontalHeader()->setResizeMode(QHeaderView::Stretch); //自适应列宽
    ui->ContentTW->horizontalHeader()->setResizeMode(QHeaderView::Stretch); //自适应列宽
    ui->SendTW->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->SendTW->hideColumn(0);
    ui->SendTW->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->ContentTW->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->ContentTW->hideColumn(0);
    ui->ContentTW->hideColumn(3);
    ui->ContentTW->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->ContentTW->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->SendTW->setSelectionMode(QAbstractItemView::SingleSelection);
    //材料报送界面的初始化设置
    connect(ui->SendTW->horizontalHeader(),SIGNAL(sectionClicked(int)),this,SLOT(MSshowsort(int)));
    QSqlQuery query;
    query.exec("select *from ZZB.MaterialSend limit 20");

    while(query.next())
    {
        ui->SendTW->insertRow(0);
        QString ms1=query.value(0).toString();
        ui->SendTW->setItem(0,0,new QTableWidgetItem(ms1));

        QString ms2=query.value(1).toString();
        ui->SendTW->setItem(0,1,new QTableWidgetItem(ms2));

        QString ms3=query.value(2).toString();
        ui->SendTW->setItem(0,2,new QTableWidgetItem(ms3));

        QString ms4=query.value(3).toString();
        ui->SendTW->setItem(0,3,new QTableWidgetItem(ms4));

        QString ms5=query.value(4).toString();
        ui->SendTW->setItem(0,4,new QTableWidgetItem(ms5));

        QString ms6=query.value(5).toString();
        ui->SendTW->setItem(0,5,new QTableWidgetItem(ms6));

        QString ms7=query.value(6).toString();
        ui->SendTW->setItem(0,6,new QTableWidgetItem(ms7));

        QString ms8=query.value(7).toString();
        ui->SendTW->setItem(0,7,new QTableWidgetItem(ms8));
    }
}

void MSwidget::MSshowdatabase()
{
    int i=ui->SendTW->rowCount();
    ui->SendTW->clearContents();
    ui->SendTW->setRowCount(0);
    QSqlQuery query;
    query.exec("select *from ZZB.MaterialSend");

    while(query.next())
    {
        ui->SendTW->insertRow(0);
        QString ms1=query.value(0).toString();
        ui->SendTW->setItem(0,0,new QTableWidgetItem(ms1));

        QString ms2=query.value(1).toString();
        ui->SendTW->setItem(0,1,new QTableWidgetItem(ms2));

        QString ms3=query.value(2).toString();
        ui->SendTW->setItem(0,2,new QTableWidgetItem(ms3));

        QString ms4=query.value(3).toString();
        ui->SendTW->setItem(0,3,new QTableWidgetItem(ms4));

        QString ms5=query.value(4).toString();
        ui->SendTW->setItem(0,4,new QTableWidgetItem(ms5));

        QString ms6=query.value(5).toString();
        ui->SendTW->setItem(0,5,new QTableWidgetItem(ms6));

        QString ms7=query.value(6).toString();
        ui->SendTW->setItem(0,6,new QTableWidgetItem(ms7));

        QString ms8=query.value(7).toString();
        ui->SendTW->setItem(0,7,new QTableWidgetItem(ms8));
    }
    int j=ui->SendTW->rowCount();
    if(i!=0&&j>i){ui->SendTW->selectRow(0);}
}

void MSwidget::on_MSeditbtn_clicked()
{
    int i=ui->SendTW->currentRow();
    if(i>-1){
   MSeditmanDialog mseditman(this);
   connect(this,SIGNAL(sendData(QStringList)),&mseditman,SLOT(receiveD(QStringList)));
   QList<QTableWidgetItem*>items=ui->SendTW->selectedItems();
      QString str = ui->SendTW->item(i,0)->text();
      QString date=items.at(0)->text();
      QString unit=items.at(1)->text();
      QString sendm=items.at(2)->text();
      QString receives=items.at(3)->text();
      QString receivephone=items.at(4)->text();
      QString envelope=items.at(5)->text();
      QString copies=items.at(6)->text();
      QStringList fan;
      fan<<str<<date<<unit<<sendm<<receives<<receivephone<<envelope<<copies;
   emit sendData(fan);
   mseditman.exec();
}
    else{
            QMessageBox::information(this, tr("提示信息"), tr("无法编辑：未选中数据"));
    }
    on_MSseekbtn_clicked();
}

void MSwidget::on_MSaddbtn_clicked()
{
    MSaddmanDialog msaddman(this);
    msaddman.exec();
}

void MSwidget::on_MSseekbtn_clicked()
{
    QString select;
    if(ui->SendTW->currentRow()>-1)
        select=ui->SendTW->item(ui->SendTW->currentRow(),0)->text();
    ui->SendTW->clearContents();
    ui->SendTW->setRowCount(0);
    ui->ContentTW->clearContents();
    ui->ContentTW->setRowCount(0);
    QString Unititem=ui->MSunitlE->text();
    QString sendman=ui->MSsendmanlE->text();
    bool unitok=Unititem.isEmpty();
    bool sendmanok=sendman.isEmpty();
    bool startok=ui->MSstartCB->isChecked();
    bool endok=ui->MSendCB->isChecked();

    QString unitstr;
    QString sendmanstr;
    QString startstr;
    QString endstr;
    QString str;
int i=0;

if(!unitok){
    unitstr=QString(" WHERE SendUnit='%1'").arg(ui->MSunitlE->text());
i=1;}
if(!sendmanok){
    if(i==0){sendmanstr=QString(" WHERE SendMan='%1'").arg(ui->MSsendmanlE->text());
    i=1;}
    else{sendmanstr=QString(" AND SendMan='%1'").arg(ui->MSsendmanlE->text());}
}
if(startok){
    if(i==0){startstr=QString(" WHERE SendDate>='%1'").arg(ui->MSstartdE->text());
        i=1;}
    else{startstr=QString(" AND SendDate>='%1'").arg(ui->MSstartdE->text());
}}
if(endok){
    if(i==0){endstr=QString(" WHERE SendDate<='%1'").arg(ui->MSenddE->text());
    i=1;}
    else{endstr=QString(" AND SendDate<='%1'").arg(ui->MSenddE->text());}}
str=QString("SELECT *FROM MaterialSend"+unitstr+sendmanstr+startstr+endstr);
    QSqlQuery query;
 if(query.exec(str))
     {
     qDebug()<<"成功";
 }else{QMessageBox::critical(this, tr("出现错误"), tr("查询失败!"));}

 while(query.next())
{
    ui->SendTW->insertRow(0);
    QString ms1=query.value(0).toString();
    ui->SendTW->setItem(0,0,new QTableWidgetItem(ms1));

    QString ms2=query.value(1).toString();
    ui->SendTW->setItem(0,1,new QTableWidgetItem(ms2));

    QString ms3=query.value(2).toString();
    ui->SendTW->setItem(0,2,new QTableWidgetItem(ms3));

    QString ms4=query.value(3).toString();
    ui->SendTW->setItem(0,3,new QTableWidgetItem(ms4));

    QString ms5=query.value(4).toString();
    ui->SendTW->setItem(0,4,new QTableWidgetItem(ms5));

    QString ms6=query.value(5).toString();
    ui->SendTW->setItem(0,5,new QTableWidgetItem(ms6));

    QString ms7=query.value(6).toString();
    ui->SendTW->setItem(0,6,new QTableWidgetItem(ms7));

    QString ms8=query.value(7).toString();
    ui->SendTW->setItem(0,7,new QTableWidgetItem(ms8));
}
 if(select.toInt()>0){
     for(int j=0;j<ui->SendTW->rowCount();j++)
         {
        if(ui->SendTW->item(j,0)->text().toInt()==select.toInt()){
            ui->SendTW->selectRow(j);
        on_SendTW_cellClicked(j,0);//为了显示材料内容表中的函数
        }
     }
 }//编辑之后，调用的是查找函数，在这里默认选中编辑行并显示相关的材料内容
}

void MSwidget::on_MSdeletebtn_clicked()
{
    if(ui->SendTW->currentRow()>-1){
            QString ID=ui->SendTW->item(ui->SendTW->currentRow(),0)->text();
            QSqlQuery query;
            QString strsql=QString("DELETE FROM MaterialSend WHERE SendID='%1'").arg(ID);
            if(query.exec(strsql))
            {QMessageBox::information(this,"提示信息","删除成功!");}
            else
            {QMessageBox::information(this,"提示信息","删除失败!");}
    }else{QMessageBox::information(this,"提示信息","未选删除行!");}
    on_MSseekbtn_clicked();
}

void MSwidget::on_SendTW_cellClicked(int row, int column)
{
    ui->ContentTW->setRowCount(0);
    int i=row,j=column;
    if(i>-1||j>-1){
    QString ID=ui->SendTW->item(i,0)->text();
    QSqlQuery q;
    QString judge=QString("select *from ZZB.Materials where SendID='%1'").arg(ID.toInt());
    q.exec(judge);
    while(q.next())
    {
        ui->ContentTW->insertRow(0);
        QString p=q.value(0).toString();
        ui->ContentTW->setItem(0,0,new QTableWidgetItem(p));

        QString o=q.value(1).toString();
        ui->ContentTW->setItem(0,1,new QTableWidgetItem(o));

        QString i=q.value(2).toString();
        ui->ContentTW->setItem(0,2,new QTableWidgetItem(i));

        QString u=q.value(3).toString();
        ui->ContentTW->setItem(0,3,new QTableWidgetItem(u));
    }
}
}

void MSwidget::on_MSaddrelatedbtn_clicked()
{
    int i=ui->SendTW->currentRow();
    if(i>-1){
    int number=ui->SendTW->item(i,7)->text().toInt();
    int numbers=ui->ContentTW->rowCount();
    if(numbers>=number){
        QMessageBox::information(this,"提示信息","该信息份数已经填写完毕,如需继续添加请增加份数数量!");
    }else{
    MSaddconDialog msaddcon(this);
    connect(this,SIGNAL(sendDat(int,int)),&msaddcon,SLOT(receivedata(int,int)));
    int str = ui->SendTW->item(i,0)->text().toInt();
    int num=ui->SendTW->item(i,7)->text().toInt()-ui->ContentTW->rowCount();
    emit sendDat(str,num);
    msaddcon.exec();
    }}
    else{QMessageBox::information(this,"提示信息","未选中添加材料行!");}
}

void MSwidget::MSshowcontent(int AID)
{
    ui->ContentTW->clearContents();
    ui->ContentTW->setRowCount(0);
    QSqlQuery q;
    QString judge=QString("select *from ZZB.Materials where SendID='%1'").arg(AID);
    q.exec(judge);
    while(q.next())
    {
        ui->ContentTW->insertRow(0);
        QString p=q.value(0).toString();
        ui->ContentTW->setItem(0,0,new QTableWidgetItem(p));

        QString o=q.value(1).toString();
        ui->ContentTW->setItem(0,1,new QTableWidgetItem(o));

        QString i=q.value(2).toString();
        ui->ContentTW->setItem(0,2,new QTableWidgetItem(i));

        QString u=q.value(3).toString();
        ui->ContentTW->setItem(0,3,new QTableWidgetItem(u));
    }
}

void MSwidget::on_MSdeleterelatedbtn_clicked()
{
    if(ui->SendTW->currentRow()>-1){
    if(ui->ContentTW->currentRow()>-1){
    QString ID=ui->ContentTW->item(ui->ContentTW->currentRow(),0)->text();
    QSqlQuery query;
    QString strsql=QString("DELETE FROM Materials WHERE MaterialsID='%1'").arg(ID);
            if(query.exec(strsql))
            {QMessageBox::information(this,"提示信息","删除成功!");}
            else
            {QMessageBox::information(this,"提示信息","删除失败!");}
    }
    else{QMessageBox::information(this, tr("提示信息"), tr("请选中删除行数据"));}
    }
    else{QMessageBox::information(this, tr("提示信息"), tr("无法删除：未选中数据"));}
    MSshowcontent(ui->SendTW->item(ui->SendTW->currentRow(),0)->text().toInt());
}

void MSwidget::on_MSupbtn_clicked()
{
    int m_CurrentRow = ui->ContentTW->currentRow();//获取当前行的Index
    if (m_CurrentRow != -1)//如果选中了数据，（未选择数据之前，返回值是-1）
    {
        if (m_CurrentRow != 0)//如果选定行不在第一行
        {
            MSSwapTwoRow(m_CurrentRow, m_CurrentRow - 1);
            ui->ContentTW->setCurrentCell(m_CurrentRow - 1, QItemSelectionModel::Select);//移动过后继续选定该行
        }
    }else {
        if (ui->ContentTW->rowCount() != 0)//如果有数据，但是currentRow=--1 说明没有选择数据,把焦点定位到第一行
        {QMessageBox::critical(this, tr("出现错误"), tr("无法移动：未选中数据"));}
        else
        {QMessageBox::critical(this, tr("出现错误"), tr("无法移动：表格没有数据"));}
    }
}

void MSwidget::on_MSdownbtn_clicked()
{
    int m_CurrentRow = ui->ContentTW->currentRow();
    if (m_CurrentRow != -1)//如果选中了一行
    {
        if (m_CurrentRow != (ui->ContentTW->rowCount() - 1))//如果不是最后一行
        {
            MSSwapTwoRow(m_CurrentRow, m_CurrentRow + 1);
            ui->ContentTW->setCurrentCell(m_CurrentRow + 1, QItemSelectionModel::Select);//移动过后继续选定该行
        }}
    else {
        if (ui->ContentTW->rowCount() != 0)//如果有数据，但是currentRow=--1 说明没有选择数据,把焦点定位到第一行
        {QMessageBox::critical(this, tr("出现错误"), tr("无法移动：未选中数据")); }
        else
        {QMessageBox::critical(this, tr("出现错误"), tr("无法移动：表格没有数据"));}
    }
}

void MSwidget::MSSwapTwoRow(int selectRow, int targetRow) {
    QStringList selectRowLine, targetRowLine;//创建两个QStringList用于储存表格数据
    int rowCount=3;//三列
    for (int i = 0; i < rowCount; i++)
    {
        selectRowLine.append(ui->ContentTW->item(selectRow, i)->text());//获取文本，并添加进QStringLine
        targetRowLine.append(ui->ContentTW->item(targetRow, i)->text());
    }
    for (int i = 0; i < rowCount; i++)
    {
        ui->ContentTW->setItem(selectRow, i, new QTableWidgetItem(targetRowLine.at(i)));//设置文本
        ui->ContentTW->setItem(targetRow, i, new QTableWidgetItem(selectRowLine.at(i)));
    }
}

void MSwidget::on_MSstartCB_clicked()
{
    bool ok;
    ok=ui->MSstartdE->isEnabled();
    if(ok){ui->MSstartdE->setEnabled(false);}
    else
    {ui->MSstartdE->setEnabled(true);}
}

void MSwidget::on_MSendCB_clicked()
{
    bool ok;
    ok=ui->MSenddE->isEnabled();
    if(ok){ui->MSenddE->setEnabled(false);}
    else
    {ui->MSenddE->setEnabled(true);}
}

void MSwidget::on_MSpreviewbtn_clicked()
{
    int i=ui->SendTW->currentRow();
    if(i>-1){
    QString filePth = QCoreApplication::applicationDirPath() + "/";
        QString fileName = QFileDialog::getSaveFileName(this, tr("导出PDF文件"), filePth, "*.pdf");
        if (!fileName.isEmpty())
        {
            // 如果文件后缀为空，则默认使用.pdf
            if (QFileInfo(fileName).suffix().isEmpty())
            {fileName.append(".pdf");}
            QPrinter *printer = new QPrinter(QPrinter::ScreenResolution);
            // 指定输出格式为pdf
            printer->setPageSize(QPrinter::A4);
            printer->setOutputFormat(QPrinter::PdfFormat);
            printer->setOutputFileName(fileName);
            QTextDocument text_document;
            text_document.setHtml(MSsaveHtmlToPDF(fileName));
            text_document.print(printer);
            text_document.end();
        }
    }else{QMessageBox::information(this,"提示信息","未选择打印条目行!");}
}


QString MSwidget::MSsaveHtmlToPDF(QString Q)
{
    QString html = "";
    html += "<html>";
    html += "<head>";
    html += "<title>"+Q+"</title>";
    html += "<head>";
    html += "<body>";
    html += "<h1>材料报送信息</h1>";
    html += "<font size=\"4\" face=\"arial\">";
    html += "<table width=\"100%\" border=\"1\" cellspacing=\"0\" cellpadding=\"0\" align=\"center\">";
    html += "<tr>";
        html += "<th colspan=\"4\">材料报送表</th>";
    html += "</tr>";
        html += "<tr>";
            html += "<td align=\"center\">报送日期</td>";
            html += "<td align=\"center\">"+ui->SendTW->item(ui->SendTW->currentRow(),1)->text()+"</td>";
            html += "<td align=\"center\">信封号</td>";
            html += "<td align=\"center\">"+ui->SendTW->item(ui->SendTW->currentRow(),6)->text()+"</td>";
        html += "</tr>";

        html += "<tr>";
            html += "<td align=\"center\">报送单位</td>";
            html += "<td align=\"center\">"+ui->SendTW->item(ui->SendTW->currentRow(),2)->text()+"</td>";
            html += "<td align=\"center\">接收方</td>";
            html += "<td align=\"center\">"+ui->SendTW->item(ui->SendTW->currentRow(),4)->text()+"</td>";
        html += "</tr>";
        html += "<tr>";
            html += "<td align=\"center\">报送人</td>";
            html += "<td align=\"center\">"+ui->SendTW->item(ui->SendTW->currentRow(),3)->text()+"</td>";
            html += "<td align=\"center\">接收方电话</td>";
            html += "<td align=\"center\">"+ui->SendTW->item(ui->SendTW->currentRow(),5)->text()+"</td>";
        html += "</tr>";
        html += "<tr>";
            html += "<td align=\"center\">份数</td>";
            html += "<td align=\"center\">"+ui->SendTW->item(ui->SendTW->currentRow(),7)->text()+"</td>";
        html += "</tr>";
    html += "</table>";
    html += "<table width=\"100%\" border=\"1\" cellspacing=\"0\" cellpadding=\"0\" align=\"center\">";
    html += "<tr>";
        html += "<th colspan=\"2\">材料内容</th>";
    html += "</tr>";
        html += "<tr>";
            html += "<td align=\"center\">材料人或名称</td>";
            html += "<td align=\"center\">材料相关内容</td>";
        html += "</tr>";
    for(int i=0;i<ui->SendTW->item(ui->SendTW->currentRow(),7)->text().toInt();i++){
        html += "<tr>";
            html += "<td align=\"center\">"+ui->ContentTW->item(i,1)->text()+"</td>";
            html += "<td align=\"center\">"+ui->ContentTW->item(i,2)->text()+"</td>";
        html += "</tr>";
}
    html += "</table>";
    html += "</font>";
    html += "</body>";
    html += "</html>";
return html;
}

void MSwidget::MSshowsort(int clounm)
{
    if(identification==1){
    ui->SendTW->sortItems(clounm,Qt::DescendingOrder);
    identification=0;}
    else{ui->SendTW->sortItems(clounm,Qt::AscendingOrder);
    identification=1;}
}
